var Track = function(){

    return {
        init: function () {

        if (!jQuery().dataTable) { 
            return;
        }    


    	var table = $("#tracks_table").dataTable({
            "sPaginationType": "bootstrap",
            // "aoColumnDefs": [
            //     { 'bSortable': false, 'aTargets': [0] },
            //     { "bSearchable": false, "aTargets": [ 0 ] }
            // ],
            "processing": true,
            "bServerSide": true,
            "sAjaxSource": "sale/track_db",
            // "sPaginationType": "full_numbers",
            "iDisplayLength": 10,
            "fnServerData": function (sSource, aoData, fnCallback) {
                $.ajax
                ({
                    'dataType': 'json',
                    'type': 'POST',
                    'url': sSource,
                    'data': aoData,
                    'success': fnCallback
                });
            },
             "aaSorting": [
                [ 6, "desc" ]],        
             "aoColumns": [
                { "mData": "checkbox","bSortable":false  },
                { "mData": "title" },
                { "mData": "student_name" },
                { "mData": "content" },
                { "mData": "track_wish" }, 
                { "mData": "track_result" }, 
                { "mData": "track_date" ,"bSearchable":false},          
                { "mData": "next_track_date" ,"bSearchable":false},
                { "mData": "nickname" },
                { "mData": "actions" }
            ],
            "fnDrawCallback": function( oSettings ) { // run some code on table redraw
                App.initUniform($('input[type="checkbox"]', table));  // reinitialize uniform checkboxes on each table reload
            }
        });


    if (jQuery().datepicker) {
            $('.date-picker').datepicker({
                format: 'yyyy-mm-dd',
                autoclose: true
            });
            // $('body').removeClass("modal-open"); // fix bug when inline picker is used in modal
        }


    jQuery('#tracks_table .group-checkable').change(function () {
            var set = jQuery(this).attr("data-set");
            var checked = jQuery(this).is(":checked");
            jQuery(set).each(function () {
                if (checked) {
                    $(this).attr("checked", true);
                    $(this).parents('tr').addClass("active");
                } else {
                    $(this).attr("checked", false);
                    $(this).parents('tr').removeClass("active");
                }                    
            });
            jQuery.uniform.update(set);
        });

    jQuery('#tracks_table').on('change', 'tbody tr .checkboxes', function(){
            $(this).parents('tr').toggleClass("active");
        });

    $(document).on('click','.clue_track_btn',function(e){
        //获取姓名
        var id = $(this).attr('data-pk');
        //var name = $(this).attr('data-title');
        var td =  $(this).parents('tr').children('td');
        var name =td.eq(1).text() +'('+td.eq(2).text()+')'; 
        console.log(name);
        if(id == '')
        {
            e.preventDefault();
            return;
        }
        $('#track_modal').on('shown.bs.modal', function (e) {
            $("#student_name").val(name);
            $("#student_id").val(id);
        });
    });

    // 删除追踪
    $(document).on("click",".track_del_btn", function(e) {

        var track = $(this).parents("tr");
        //获取id
        var id = $(this).attr('data-pk');

        bootbox.confirm("是否删除该条记录?", function(result) {
            if(result!=null&&result!=false)
            {
                //ajax删除
                $.ajax({
                    url: 'sale/track_del',
                    type: 'POST',
                    dataType: 'json',
                    data: {id: id},
                })
                    .done(function(response) {
                        if(response.code==0){
                            toastr.success(response.msg);
                            track.remove();
                        } else {
                            toastr.error(response.msg);
                        }
                    })
                    .fail(function() {
                        console.log("error");
                    })
                    .always(function() {
                        console.log("complete");
                    });

            }
        });
    });



            //记录范围选择
    $(document).on('change','#track_range_select',function(){
        var url = $("#track_range_select option:selected").val();
        if(url != window.location.href)
        {
            window.location.href = url;
        }
    });

    //转移记录
    jQuery("#track_dist_btn").on('click',function(){
        var ids = get_check_value();
        console.log(ids);
        if(ids !="")
        {
            $("#dist_modal #track_ids").val(ids);
        } else {
            alert("请至少选择一条记录");
            return false;
        }
    });

    //转移提交
    jQuery("#dist_submit_btn").on('click',function(){
        var ids = $("#track_ids").val();
        var new_owner = $("#new_owner").val();
        // alert(ids);
        if (ids && new_owner)
        {
            $.ajax({
                url: 'sale/track_dist',
                type:'post',
                dataType: 'json',
                data:{'ids':ids,'owner':new_owner}
            }).always(function () {
            }).done(function (responseText) {
                if(responseText.code==0){
                    toastr.success(responseText.msg);
                    $("#dist_modal").modal('hide');
                    // setTimeout(function(){window.location.reload()}, 3000);
                    if(table) {
                        table.fnClearTable(false);
                        table.fnDraw();
                    }
                } else {
                    toastr.error(responseText.msg);
                }
            });
        }
    });

    //清空隐藏值
    jQuery('#dist_modal').on('hidden.bs.modal', function (e) {
            $("#track_ids").val();
            $(this).removeData('modal');
        });


    //select2初始化

    $("#track_clues").select2({
        placeholder: "选择线索",
        minimumInputLength: 1,
        ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
            url: "ajax_all",
            dataType: 'jsonp',
            data: function (term, page) {
                return {
                    q: term, // search term
                    page_limit: 10,
                    apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
                };
            },
            results: function (data, page) { // parse the results into the format expected by Select2.
                // since we are using custom formatting functions we do not need to alter remote JSON data
                return {
                    results: data.clues
                };
            }
        },
        // initSelection: function (element, callback) {
        //     // the input tag has a value attribute preloaded that points to a preselected movie's id
        //     // this function resolves that id attribute to an object that select2 can render
        //     // using its formatResult renderer - that way the movie name is shown preselected
        //     var id = $(element).val();
        //     if (id !== "") {
        //         $.ajax("http://api.rottentomatoes.com/api/public/v1.0/movies/" + id + ".json", {
        //             data: {
        //                 apikey: "ju6z9mjyajq2djue3gbvv26t"
        //             },
        //             dataType: "jsonp"
        //         }).done(function (data) {
        //             callback(data);
        //         });
        //     }
        // },
        id:'student_id',
        formatResult: function(clue){return clue.student_name+'(D-'+clue.student_id.padLeft(0,6)+')'}, // omitted for brevity, see the source of this page
        formatSelection: function(clue){return clue.student_name+'(D-'+clue.student_id.padLeft(0,6)+')'}, // omitted for brevity, see the source of this page
        dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
        escapeMarkup: function (m) {
            return m;
        } // we do not want to escape markup since we are displaying html in results
    });




    //获取checkboxes的值
    function get_check_value()
    {
        var value = "";
        $(".checkboxes").each(function(){ 
            if($(this).attr("checked")){
                value += $(this).val()+","
            }
        });

        return value;
    }


    String.prototype.padLeft = function (padChar, width) { 
        var ret = this; 
        while (ret.length < width) { 
            if (ret.length + padChar.length < width) { 
                ret = padChar + ret; 
            } 
            else { 
                ret = padChar.substring(0, width-ret.length) + ret; 
            } 
        } 
        return ret; 

        }
    }   
    };
}();   

